﻿using NetEasyMusic.Lib.Models;

// ReSharper disable StringLiteralTypo
namespace NetEasyMusic.Lib.Data;

public class Search : DataBasic
{
    public Search(string cookie) : base(cookie)
    {
    }

    public Search()
    {
    }

    public Search(string url, bool isUse = false) : base(url, isUse)
    {
    }

    public async Task<SongModel[]> SearchContext(string s)
    {
        var obj = await GetFormString($"search?keywords={s}&cookie={Cookie}");
        if (obj == null) return [];
        var context = obj["result"]!["songs"];

        return context!.Select(value => new SongModel
        {
            Id = value["id"]!.ToString(),
            Artists = value["artists"]!.Select(x => new ArtistModel(x)).ToArray(),
            Album = value["album"]!["name"]!.ToString(),
            Name = value["name"]!.ToString(),
            AlbumId = value["album"]!["id"]!.ToString(),
            PicUrl = value["album"]!["artist"]!["img1v1Url"]!.ToObject<string>()!,
            Time = value["duration"]!.ToObject<string>()!
        }).ToArray();
    }

    public async Task<SearchCollection> SearchMultiMatch(string key)
    {
        var context = await GetFormString($"/search/multimatch?keywords={key}&cookie={Cookie}");
        var result = context?["result"];
        if (result == null) return new SearchCollection();
        return new SearchCollection
        {
            Artists = result["artist"]?.Select(x => new ArtistModel()
            {
                Id = x["id"]?.ToObject<string>()!,
                Name = x["name"]?.ToObject<string>()!,
                PicUrl = x["picUrl"]?.ToObject<string>()!,
            }).ToArray() ?? [],
            PlaylistModels = result["playlist"]?.Select(x => new PlaylistModel()
            {
                Name = x["name"]!.ToObject<string>()!,
                Id = x["id"]!.ToObject<string>()!,
                CoverImgUrl = x["coverImgUrl"]!.ToObject<string>()!,
                Description = x["description"]!.ToObject<string>()!
            }).ToArray() ?? []
        };
    }

    public async Task<string> SearchContext()
    {
        var context = await GetFormString($"/search/default");
        return context?["data"]!["showKeyword"]!.ToObject<string>()!;
    }

    public async Task<string[]> HotSearch()
    {
        var context = await GetFormString("/search/hot");
        return context?["result"]!["hots"]!.Select(x => x["first"]!.ToObject<string>()!).ToArray() ?? [];
    }
}